﻿using Elmah;
using System;
using System.Collections;
using System.Globalization;
using TFSExceptionHandling.Domain.Model.TFS;
using TFSExceptionHandling.ElmahOnTfs.PushNotification;
using TFSExceptionHandling.ElmahOnTfs.TfsHandling;
using TFSExceptionHandling.Infrastructure.TFSHandling;

namespace TFSExceptionHandling.ElmahOnTfs
{
    public class ErrorProvider : ErrorLog
    {
        public IDictionary Config { get; set; }

        public TfsHandlingConnection TfsHandlingConnection { get; set; }

        private readonly TfsHandlingClient _tfsHandlingClient;

        public ErrorProvider(IDictionary config)
        {
            _tfsHandlingClient = new TfsHandlingClient();

            Config = config;

            var tfsHandlingConnection = new TfsHandlingConnection
                                        {
                                            TfsServer = Config["TFSServer"].ToString(),
                                            ProjectName = Config["ProjectName"].ToString(),
                                            UserName = Config["UserName"].ToString(),
                                            Password = Config["Password"].ToString(),
                                            Domain = Config["Domain"].ToString()
                                        };

            TfsHandlingConnection = tfsHandlingConnection;
        }

        public override string Log(Error error)
        {
            var workItemHandling = new WorkItemHandling
                                   {
                                       ReproSteps = error.Detail + error.WebHostHtmlMessage,
                                       Description = error.Message,
                                       WorkItemType = WorkItemTypes.Bug.ToString(),
                                       AssignedTo = Config["SendBugTo"].ToString(),
                                       Title = string.Format("{0} - {1} - {2}", error.HostName, error.ApplicationName, error.Message),
                                       TeamProject = TfsHandlingConnection.ProjectName
                                   };
            
            //Create WorkItem on TFS
            workItemHandling = _tfsHandlingClient.RegisterWorkItem(workItemHandling, TfsHandlingConnection);

            //Send Push Notifications
            var notificationClient = new NotificationClient();
            notificationClient.SendToast("Toast - Erro Encontrado", "Projeto: " + Config["ProjectName"]);
            notificationClient.SendTile("Tile - Erro Encontrado", "Projeto: " + Config["ProjectName"]);

            if (workItemHandling != null)
                return workItemHandling.Id.ToString(CultureInfo.InvariantCulture);

            throw new Elmah.ApplicationException("Não foi possível cadastrar esse erro! Contate o administrador");
        }

        /// <summary>
        /// Get a Error From Elmah on TFS
        /// </summary>
        /// <param name="id">Error Identifier (Guid)</param>
        /// <returns>Error Fetched (or Null If Not Found)</returns>
        public override ErrorLogEntry GetError(string id)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Get A Page Of Errors From Elmah on TFS
        /// </summary>
        /// <param name="pageIndex">Page Index</param>
        /// <param name="pageSize">Size Of Page To Return</param>
        /// <param name="errorEntryList">List of Errors Returned</param>
        /// <returns>Total Count of Errors</returns>
        public override int GetErrors(int pageIndex, int pageSize, IList errorEntryList)
        {
            throw new NotImplementedException();
        }
    }
}
